package com.vf.editor.mvc.resources.point;

import java.io.File;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import com.vf.editor.common.controller.BaseController;
import com.vf.editor.common.model.resources.ModelClassify;
import com.vf.editor.common.model.resources.Point;
import com.vf.editor.common.model.resources.PointClassify;
import com.vf.editor.common.util.ExcelUtil;
import com.vf.editor.common.util.UuidUtil;

@Path(value = "/resources/point", viewPath = "/views/resources/point/")
public class PointController extends BaseController{
	
	public void index() {
		this.render("list.html");
	}
	
	public void listData() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String classifyId = getPara("classifyId","1");

		String sqlExceptSelect = " FROM " + Point.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%'  ) ";
		}
		if (!StrKit.isBlank(classifyId)) {
			sqlExceptSelect += " AND O.CLASSIFYID = '" + classifyId + "'   ";
		}
		Page<Point> page = Point.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	public void save() {
		Point model = getModel(Point.class);
		if (StrKit.notBlank(model.getId())) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			String classifyIdId;
			if(StrKit.isBlank(model.getClassifyId())) {
				classifyIdId="1";
				model.setClassifyId(classifyIdId);
			}else {
				classifyIdId=model.getClassifyId();
			}
			PointClassify pointClassify=PointClassify.dao.findById(classifyIdId);
			if (model.save()) {
				try {
					if(pointClassify!=null) {
						pointClassify.setCount(pointClassify.getCount()+1);
						pointClassify.update();
					}
				}catch (Exception e) {
				}
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	@Before(Tx.class)
	public void delete() throws Exception {
		String id = getPara("id");
		Point model = Point.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！",model);
				try {
					PointClassify modelClassify=PointClassify.dao.findById(model.getClassifyId());
					if(modelClassify!=null) {
						modelClassify.setCount(modelClassify.getCount()-1);
						modelClassify.update();
					}
				}catch (Exception e) {
				}
				
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void getById() {
		String id = getPara("id");
		Point model = Point.dao.findById(id);
		if (model != null) {
			renderSuccess("成功！",model);
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	private String rootPath = PathKit.getWebRootPath();
	@Before(Tx.class)
	public void upload() {
		UploadFile uploadFile = getFile();
		try {
			String classifyId=getPara("classifyId","1");
			ModelClassify modelClassify=ModelClassify.dao.findById(classifyId);
			if(modelClassify==null) {
				renderError("无效分组，请检查是否存在!");
				return ;
			}
			String path = "/upload/point/" + uploadFile.getFileName().replace(" ", "");
			File file = new File(rootPath+path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (file.exists()) {
				file.delete();
			}
			if(uploadFile.getFile().renameTo(file)) {
				Workbook workbook=ExcelUtil.readExcel(rootPath+path);
				List<Sheet> sheets= ExcelUtil.getSheet( workbook);
				int count = 0;int success = 0;
				if(sheets!=null && sheets.size()>0) {
					for(Sheet sheet:sheets) {
						List<Row> rows=ExcelUtil.getRows(sheet);
						if(rows!=null && rows.size()>0) {
							count += rows.size()-1;
							for(int i=0;i<rows.size();i++) {
								if(i>0) {
									Row row = rows.get(i);
									List<Cell> cells=ExcelUtil.getCells(row);
									String x = cells.get(1).getStringCellValue();
									String y = cells.get(2).getStringCellValue();
									if(!StrKit.isBlank(x) && !StrKit.isBlank(y)) {
										Point point = Point.dao.findFirst("select * from "+Point.TABLE_NAME+" where x=? and y=? ",x,y);
										if(point==null) {
											point = new Point();
											point.setId(UuidUtil.getUUID());
											point.setX(x);
											point.setY(y);
											point.save();
										}
										point.setClassifyId(classifyId);
										if(!StrKit.isBlank(cells.get(0).getStringCellValue())) {
											point.setName(cells.get(0).getStringCellValue());
										}
										if(!StrKit.isBlank(cells.get(3).getStringCellValue())) {
											point.setZ(cells.get(3).getStringCellValue());
										}
										point.update();
										success++;
									}
								}
							}
						}
					}
				}
				if (file.exists()) {
					file.delete();
				}
				renderSuccess("共【"+count+"】条数据，导入成功【"+success+"】条。");
			}else {
				throw new Exception("上传失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			renderError(e.getMessage());
		}
	}

	public void saveClassify() {
		PointClassify model = getModel(PointClassify.class);
		if (StrKit.notBlank(model.getId()) ) {
			if (model.update()) {
				renderSuccess("更新成功！",model);
			} else {
				renderError("更新失败！");
			}
		} else {
			model.setId(UuidUtil.getUUID());
			if (model.save()) {
				renderSuccess("保存成功！",model);
			} else {
				renderError("保存失败！");
			}
		}
	}
	
	public void getClassifys() {
		List<PointClassify> classifies=PointClassify.dao.find("SELECT * FROM "+PointClassify.TABLE_NAME+" ORDER BY SORT ASC ");
		if (classifies!=null) {
			renderSuccess("成功！",classifies);
		} else {
			renderError("暂无分类！");
		}
	}
	
	
	public void listDataForClassify() {
		int pageNumber = getParaToInt("page", 1);
		int pageSize = getParaToInt("limit", 10);
		String keyword = getPara("keyword");
		String sqlExceptSelect = " FROM " + PointClassify.TABLE_NAME + " o  WHERE 1=1 ";
		if (!StrKit.isBlank(keyword)) {
			sqlExceptSelect += " AND ( O.NAME LIKE '%" + keyword + "%'  ) ";
		}
		sqlExceptSelect += "  ORDER BY   O.SORT ASC ";
		Page<PointClassify> page = PointClassify.dao.paginate(pageNumber, pageSize, "select * ", sqlExceptSelect);
		renderLayuiPage(0, page.getList(), "", page.getTotalRow());
	}
	
	
	
	@Before(Tx.class)
	public void deleteClassify() throws Exception {
		String id = getPara("id");
		PointClassify model = PointClassify.dao.findById(id);
		if (model != null) {
			if (model.delete()) {
				renderSuccess("删除成功！",model);
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
}
